package com.qingfeng.base.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.qingfeng.base.aop.LogInfo;
import com.qingfeng.base.aop.LogModel;
import com.qingfeng.base.model.Page;
import com.qingfeng.base.service.TUserService;
import com.qingfeng.base.util.CodeEnum;
import com.qingfeng.base.util.ResponseMessage;
import com.qingfeng.base.vo.MpCondition;
import com.qingfeng.base.vo.PageVo;
import com.qingfeng.client.api.BaseV1Api;
import com.qingfeng.client.bean.Seller;
import com.qingfeng.client.dao.SellerMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @Author:zhangyuefei
 * @Date:2019/9/6 14:21
 */
@LogModel("用户管理")
@Api(tags = "用户管理接口")
@RestController
@RequestMapping("/user")
public class UserController extends BaseV1Api {


    @Autowired
    private TUserService userService;

    @Autowired
    private SellerMapper userMapper;





    @ApiOperation("分页查询")
    @PostMapping("/query")
    @ResponseBody
    public ResponseMessage query(@RequestBody PageVo pageVo) {
        Page<Seller> page = pageVo.getPage();
        List<MpCondition> conditions = pageVo.getCondition();

        List<OrderItem> array = page.getOrders();
        if (array != null || array.size() == 0) {
            OrderItem orderItem = new OrderItem();
            orderItem.setAsc(true);
            orderItem.setColumn("id");
            List<OrderItem> orderItems = new ArrayList<>();
            orderItems.add(orderItem);
            page.setOrders(orderItems);
        }
        QueryWrapper<Seller> queryWrapper = new QueryWrapper<>();
        if (conditions != null) {
            for (int i = 0; i < conditions.size(); i++) {
                MpCondition condition = conditions.get(i);
                String operate = condition.getOperate();
                String attribute = condition.getAttribute();
                String dateFormate = condition.getDateformat();
                Object value = condition.getValue();
                if (StringUtils.isEmpty(dateFormate)) {
                    dateFormate = "%Y-%m-%d";
                }

                if (StringUtils.isEmpty(value)){
                    continue;
                }
                switch (operate) {
                    case "eq":
                        queryWrapper.eq(attribute, value);
                        break;
                    case "gt":
                        queryWrapper.gt(attribute, value);
                        break;
                    case "ge":
                        queryWrapper.ge(attribute, value);
                        break;
                    case "lt":
                        queryWrapper.lt(attribute, value);
                        break;
                    case "le":
                        queryWrapper.le(attribute, value);
                        break;
                    case "like":
                        queryWrapper.like(attribute,value);
                        break;
                    case "date_eq":
                        queryWrapper.apply("date_format(" + attribute + ",'" + dateFormate + "')={0}", value);
                        break;
                    case "date_gt":
                        queryWrapper.apply("date_format(" + attribute + ",'" + dateFormate + "')>{0}", value);
                        break;
                    case "date_ge":
                        queryWrapper.apply("date_format(" + attribute + ",'" + dateFormate + "')>={0}", value);
                        break;
                    case "date_lt":
                        queryWrapper.apply("date_format(" + attribute + ",'" + dateFormate + "')<{0}", value);
                        break;
                    case "date_le":
                        queryWrapper.apply("date_format(" + attribute + ",'" + dateFormate + "')<={0}", value);
                        break;
                    default:
                        queryWrapper.eq(attribute, value);
                        break;
                }
            }
        }
        IPage<Map<String, Object>>  page1 = userMapper.selectMapsPage(page,queryWrapper);
        return new ResponseMessage(CodeEnum.SUCCESS,page1);
    }

    @LogInfo(model = "方法级别：用户管理", action = "用户新增" ,param = "'用户新增'+#user.name")
    @ApiOperation("新增")
    @PostMapping("/save")
    public ResponseMessage save(@RequestBody Seller user){
        //将新建用户添加到当前用户店铺下
        Seller user1 = getUser();
        user.setStoreId(user1.getStoreId());
//        if (user.getAuthType()==null){
//            return new ResponseMessage(CodeEnum.ERROR,"请选择证件类型");
//        }

        String msg= userService.save(user);
        if (StringUtils.isEmpty(msg)){
            return new ResponseMessage(CodeEnum.SUCCESS, null);
        }else {
            return new ResponseMessage(CodeEnum.ERROR.getCode(),msg);
        }
    }

    @ApiOperation("修改")
    @PostMapping("/saveOrUpdate")
    @ResponseBody
    public ResponseMessage saveOrUpdate(@RequestBody Seller user){
        String msg= userService.update(user);
        if (StringUtils.isEmpty(msg)){
            return new ResponseMessage(CodeEnum.SUCCESS, null);
        }else {
            return new ResponseMessage(CodeEnum.ERROR.getCode(),msg);
        }
    }

    @ApiOperation("获取详情")
    @GetMapping("/detail/{id}")
    @ResponseBody
    public ResponseMessage detaℹil(@PathVariable Long id){
        Seller seller = userMapper.getUserById(id);
        JSONObject json = (JSONObject) JSON.toJSON(seller);
        json.remove("authorities");
        return new ResponseMessage(CodeEnum.SUCCESS,json);
    }

    @LogInfo(model = "方法级别：用户管理", action = "用户删除",param = "'用户id：'+#ids")
    @ApiOperation("删除")
    @ApiImplicitParam(name = "ids", value = "主键ids", required = true)
    @PostMapping("/delete")
    public ResponseMessage delete(@RequestBody JSONArray ids){
        List<Long> idList =  JSON.parseArray(ids.toJSONString(),Long.class);
        if (CollectionUtils.isEmpty(idList)){
            return new ResponseMessage(CodeEnum.ERROR.getCode(),"用户id为空");
        }
        int index = userService.deletes(idList);
        return new ResponseMessage(index);
    }

    @LogInfo(model = "方法级别：用户管理", action = "更新用户状态",param = "'用户id：'+#user.id+'enable:'+#user.enable")
    @ApiOperation("更新用户状态")
    @PostMapping("/updateUserState")
    public ResponseMessage updateUserState(@RequestBody Seller user){
        userMapper.updateEnableById(user.getEnable(),user.getId());
        return  new ResponseMessage(1);
    }

}
